package com.study.cloud.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.CoreSubscriber;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;


@Component
public class AuthGatewayFilterFactory extends AbstractGatewayFilterFactory<AuthGatewayFilterFactory.Config>{

    final Logger logger = LoggerFactory.getLogger(AuthGatewayFilterFactory.class);

    /**
     * 这个名称需要与config中定义的字段名称保持一致
     */
    public static final String NAME_KEY = "name";

    public AuthGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(NAME_KEY);
    }

    @Override
    public GatewayFilter apply(Config config) {

        logger.info(LocalDateTime.now().toString()+"开始:"+config.getName());

        return (exchange, chain) -> {

            logger.info(LocalDateTime.now().toString()+"开始222:"+config.getName());

            return chain.filter(exchange).then(Mono.fromRunnable(()->{
                logger.info(LocalDateTime.now().toString()+"结束:"+config.getName());
            }));};
    }

    public static class Config {

        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
